package com.aaa.back.gateway.filter;

import com.aaa.back.gateway.white.WhiteList;
import com.aaa.utils.JWTUtil;
import com.aaa.vo.Result;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @program: qy172-shop-parent
 * @description:
 * @author: 闫克起2
 * @create: 2024-03-01 09:07
 **/
@Component //表示该类的对象交于spring容器管理
public class LoginFilter implements GlobalFilter, Ordered {

    @Autowired
    private WhiteList whiteList;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.获取访问的资源路径
        String path = request.getPath().toString();
        //3.是否属于白名单--[无需认证即可访问的资源]
        List<String> list = whiteList.getList();
        if (list.contains(path)) {
            return chain.filter(exchange); //放行
        }
        //4.获取携带token---请求头
        String token = request.getHeaders().getFirst("token");
        if (token != null && JWTUtil.validate(token)&&redisTemplate.hasKey(token)) { //未来JWT--校验方法来验证token是否有效

            return chain.filter(exchange); //放行
        }

        //5. 返回一个json数据。
        Result result = new Result(402, "登录无效", null);
//3.3作JSON转换---没有引入fastjson依赖
        byte[] bytes = JSON.toJSONString(result).getBytes(StandardCharsets.UTF_8);
        //3.4调用bufferFactory方法,生成DataBuffer对象
        DataBuffer buffer = response.bufferFactory().wrap(bytes);

        //4.调用Mono中的just方法,返回要写给前端的JSON数据
        return response.writeWith(Mono.just(buffer));
    }

    //值越小优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}







